package client.comm.baoding.ui

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.view.View
import androidx.databinding.ObservableField
import client.comm.commlib.base.SimpleTextWatcher
import client.comm.commlib.toast.toast
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.BuyCartAdapter
import client.comm.baoding.api.bean.BuyCartRet
import client.comm.baoding.api.bean.ShopingBean
import client.comm.baoding.databinding.ActivityBuycartBinding
import client.comm.baoding.ui.vm.BuyCartModel
import java.math.BigDecimal
import java.util.*
import client.comm.baoding.BaseMiddleActivity

class BuyCartActivity : BaseMiddleActivity<BuyCartModel, ActivityBuycartBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_buycart
    }

    val adapterCart: BuyCartAdapter by lazy {
        BuyCartAdapter(this, mImgLoader).apply {

            changeNumItem = { b, n ->
                var lastNum = 1
                try {
                    if (!TextUtils.isEmpty(b.selectNum.get())) {
                        lastNum = b.selectNum.get()!!.toInt() + n
                    }
                } catch (e: Exception) {
                }

                if (lastNum < 1)
                    lastNum = 1
                b.selectNum.set("${lastNum}")
            }

            textWatcher = object : SimpleTextWatcher() {
                override fun afterTextChanged(s: Editable?) {
                    super.afterTextChanged(s)
                    updatePrice()
                }
            }

            changeCheckItem = {
                it.isCheck.set(!it.isCheck.get()!!)
                updataAllCheck()
                updatePrice()
            }
        }
    }

    fun updataAllCheck() {
        var bbb = true
        for (i in adapterCart.getItems()) {
            i?.let {
                if (it.isCheck.get() == false) {
                    bbb = false
                }
            }
        }
        viewModel.isCheckAll.value = bbb
    }

    override fun initViewModel(): BuyCartModel = createViewModel()

    override fun initView() {
        binding.vm = viewModel
        binding.event = this

        binding.recyclerView.adapter = adapterCart
        binding.emptyLayout.setOnClickListener {
            viewModel.callBuyCart()
        }
        viewModel.callBuyCart.observe(this, {
            it?.apply {
                if (it.isSuccess) {
                    val list = ArrayList<BuyCartRet.Shopping>()

                    for (i in it.data!!.shopping_list) {
                        i.selectNum = ObservableField("${i.num}")
                        i.isCheck = ObservableField<Boolean>(false)
                        list.add(i)
                    }

                    viewModel.isCheckAll.value = false
                    viewModel.isEditMode.value = "编辑"
                    viewModel.isEditModeVal.value = true

                    if (list.size > 0) {

                        adapterCart.submitList(list)
                        updatePrice()
                        binding.emptyLayout.visibility = View.GONE

                    } else {
                        binding.emptyLayout.errorType = EmptyLayout.NODATA
                    }

                } else {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })
        viewModel.delRet.observe(this, {
            it?.apply {
                if (it.isSuccess) {
                    toast("成功")
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                    viewModel.callBuyCart()
                }
            }
        })

    }

    override fun onResume() {
        super.onResume()
        val bbb = false
        viewModel.isCheckAll.value = bbb

        for (i in adapterCart.getItems()) {
            i?.let {
                it.isCheck.set(bbb)
            }
        }
        updatePrice()

        viewModel.callBuyCart()
    }

    fun editAll() {//改变编辑模式
        val bbb = false
        viewModel.isCheckAll.value = bbb
        for (i in adapterCart.getItems()) {
            i?.let {
                it.isCheck.set(bbb)
            }
        }
        viewModel.isEditMode.value = if (viewModel.isEditMode.value!!.equals("编辑")) "取消" else "编辑"
        viewModel.isEditModeVal.value =
            if (viewModel.isEditMode.value!!.equals("编辑")) true else false
        updatePrice()
    }

    //改变全选中状态
    fun changeAllCheck() {
        val bbb = !viewModel.isCheckAll.value!!
        viewModel.isCheckAll.value = bbb
        for (i in adapterCart.getItems()) {
            i?.let {
                it.isCheck.set(bbb)
            }
        }
        updatePrice()
    }

    fun updatePrice() {
        var number: BigDecimal = BigDecimal(0)
        val items = adapterCart.getItems()
        for (b in items) {
            b?.let {

                if (it.isCheck.get() == true && !TextUtils.isEmpty(it.selectNum.get())) {
                    var num = 0;
                    try {
                        if (!TextUtils.isEmpty(it.selectNum.get())) {
                            num = it.selectNum.get()!!.toInt()
                        }
                    } catch (e: Exception) {
                    }
                    if (num > 0) {
                        number = number.add(BigDecimal(num).multiply(BigDecimal(b.price)))
                    }
                }
            }
        }
        binding.price = "${number.toDouble()}"
    }

    //确认订单
    fun ok() {
        val list = ArrayList<ShopingBean>()
        for (i in adapterCart.getItems()) {
            i?.let {
                var num: Int = 0
                try {
                    it.selectNum?.get()?.apply {
                        num = this.toInt()
                    }
                } catch (e: Exception) {
                }
                if (it.isCheck.get() == true && num > 0) {
                    it.num = num
                    val bbb = ShopingBean(
                        goods_id = it.goods_id,
                        goods_img = it.goods_img,
                        name = it.name,
                        price = it.price,
                        shopping_id = it.shopping_id,
                        num = it.num,
                        sku = it.sku,
                        store_id = it.store_id,
//                        old_price = it.old_price,
//                        lpq_price = it.lpq_price,
                        integral = it.integral,
////                        integral_f = it.integral_f,
//                        price_r = it.price_r,
//                        create_time = it.create_time
                    )
                    list.add(bbb)
                }
            }
        }

        if (list.size == 0) {
            toast("请选中商品后再提交")
        } else {
            startActivity(
                Intent(
                    this,
                    ConfirmOrderActivity::class.java
                ).apply {
                    putExtra("list", list)
                })
        }
    }

    fun del() {
        val list = ArrayList<BuyCartRet.Shopping>()
        for (i in adapterCart.getItems()) {
            i?.let {
                if (it.isCheck.get() == true) {
                    list.add(it)
                }
            }
        }
        if (list.size == 0) {
            toast("请选中商品后再提交")
            return
        }
        viewModel.delCart(list)
    }
}